package cn.otrue.patienthealthmanager.utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;
import cn.otrue.patienthealthmanager.HealthApplication;
import cn.otrue.patienthealthmanager.R;
import cn.otrue.patienthealthmanager.fragment.BaseFragment;
import cn.otrue.patienthealthmanager.fragment.MainDataPickFragment;

/**
 * 通用工具类
 * 
 * @author G
 * 
 */
public class CommonUtil {

	public static final int NETWORK_TYPE_MOBILE_OTHER = 20;
	public static final int NETWORK_TYPE_WIFI = 1;
	public static final int NETWORK_TYPE_MOBILE = 2;
	public static final int NETWORK_TYPE_MOBILE_2G = 21;
	public static final int NETWORK_TYPE_MOBILE_3G = 22;
	public static final int NETWORK_TYPE_MOBILE_4G = 23;
	public static final int NETWORK_TYPE_MOBILE_NONE = -1;

	/**
	 * 把dp根据当前屏幕密度转换成px
	 * 
	 * @param context
	 * @param dpValue
	 * @return
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	public static void getHig(Activity activty) {
		activty.getWindowManager();
	}

	/**
	 * 获取当前屏幕密度指数
	 * 
	 * @param context
	 * @return
	 */
	public static float getCurrentScale(Context context) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return scale;
	}

	/**
	 * 防止按钮短时间连续点击
	 */
	private static long lastClickTime;

	public static boolean isFastDoubleClick() {
		long time = System.currentTimeMillis();
		if (time - lastClickTime < 500) {
			return true;
		}
		lastClickTime = time;
		return false;
	}

	/**
	 * 弹一个Toast
	 * 
	 * @param msg
	 *            要展示的信息
	 * @param lengthType
	 *            展示的时间长度（0--短，1--长）
	 */
	public static void showToast(String msg, int lengthType) {
		if (0 == lengthType)
			Toast.makeText(HealthApplication.getInstance(), msg,
					Toast.LENGTH_SHORT).show();
		else if (1 == lengthType)
			Toast.makeText(HealthApplication.getInstance(), msg,
					Toast.LENGTH_LONG).show();
		else
			Toast.makeText(HealthApplication.getInstance(), msg,
					Toast.LENGTH_SHORT).show();
	}

	/**
	 * 弹一个Toast
	 * 
	 * @param msg
	 *            显示自定义吐司
	 * @param lengthType
	 *            展示的时间长度（0--短，1--长）
	 * @param activty
	 */
	public static void showToast(String msg, int lengthType, Activity activty) {
		int showType;
		if (0 == lengthType)
			showType = Toast.LENGTH_SHORT;
		else if (1 == lengthType)
			showType = Toast.LENGTH_LONG;
		else
			showType = Toast.LENGTH_LONG;
		LayoutInflater inflater = activty.getLayoutInflater();
		View layout = inflater.inflate(R.layout.item_toast_layout,
				(ViewGroup) activty.findViewById(R.id.toast_layout_root));
		TextView title = (TextView) layout.findViewById(R.id.toast_text);
		title.setText(msg);
		Toast toast = new Toast(HealthApplication.getInstance());
		float bar_height = ((Context) activty).getResources().getDimension(
				R.dimen.title_bar_height);
		toast.setGravity(Gravity.TOP, 0, (int) bar_height + 2);
		toast.setDuration(showType);
		toast.setView(layout);
		toast.show();
	}

	/**
	 * 判断网络是否链接
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isNetConnected(Context context) {

		int netType = NetCheckUtil.getNetType(context);
		if (netType != NETWORK_TYPE_MOBILE_NONE) {
			return true;
		}
		return false;
	}

	/**
	 * 读取清单文件中的配置项 一般用于获取ApiKey
	 * 
	 * @param context
	 * @param metaKey
	 *            key的名称
	 * @return 如果没有就返回 Null,使用时注意非判断
	 */
	public static String getMetaValue(Context context, String metaKey) {
		Bundle metaData = null;
		String apiKey = null;
		if (context == null || metaKey == null) {
			return null;
		}
		try {
			ApplicationInfo ai = context.getPackageManager()
					.getApplicationInfo(context.getPackageName(),
							PackageManager.GET_META_DATA);
			if (null != ai) {
				metaData = ai.metaData;
			}
			if (null != metaData) {
				apiKey = (String) metaData.get(metaKey);
			}
		} catch (NameNotFoundException e) {
			return null;
		}
		return apiKey;
	}

	/**
	 * 根据输入的数据返回相应的健康评论（指导意见）
	 * 
	 * @param addType
	 *            分析对象的类型（血压、血糖等）MainDataPickFragment.ADDTYPE_PLUS
	 * @param float1
	 *            数据1（餐前、高压）
	 * @param float2
	 *            数据2（餐后、低压）
	 * @return
	 */
	public static String getAdviseByData(int addType, float float1, float float2) {
		String advise = "";
		// 数据是否正常 0 异常 1-正常
		switch (addType) {
		case MainDataPickFragment.ADDTYPE_PLUS:// 评价 心率正常范围为50—95次/分。
			if (float1 < 60) {
				advise = "您的心跳稍慢，请及时咨询医生";
			} else if (float1 <= 100 && float1 >= 60) {
				advise = "您的心脏很健康";
			} else {
				advise = "您的心跳太快啦，冷静一会儿";
			}
			break;
		case MainDataPickFragment.ADDTYPE_PRESSURE_HIGH:
		case MainDataPickFragment.ADDTYPE_PRESSURE_LOW:

			if (float2 >= 60 && float2 <= 85 && float1 >= 90 && float1 <= 130) {
				advise = "您的血压很正常，继续保持哟";
			} else if (float2 > 85 && float2 <= 90 && float1 > 130
					&& float1 <= 140) {
				advise = "您的血压偏高，要重视啊";// 高血压前期：高压在130~139mmHg和/或低压在85~89mmHg。
			} else if (float2 > 90 || float1 > 140) {
				advise = "您的血压异常，按时吃药哈";
			} else if (float2 < 60 || float1 < 90) {
				advise = "您的血压太低，请及时就诊";
			} else {
				advise = "您的血压很正常，继续保持哟";
			}
			break;
		case MainDataPickFragment.ADDTYPE_SUGAR_AFTERMEAL:// 评价餐后血糖
															// 餐后2小时血糖值：≤3.9≤9.4毫摩/升。
			if (float2 < 3.9) {
				advise = "您的血糖偏低，咱再吃点?";
			} else if (float2 <= 9.4 && float2 >= 3.9) {
				advise = "您的血糖正常，请继续保持哟~";
			} else {
				advise = "您的血糖偏高，请及时咨询医生";
			}
			break;
		case MainDataPickFragment.ADDTYPE_SUGAR_BEFOREMEAL:// 评价餐前血糖
															// 空腹血糖正常值：3.9～6.1毫摩尔/升。
			if (float1 < 3.9) {
				advise = "您的空腹血糖低啦，吃点东西吧";
			} else if (float1 <= 6.1 && float1 >= 3.9) {
				advise = "您的空腹血糖正常，请继续保持哟~";
			} else {
				advise = "您的空腹血糖偏高，请及时咨询医生~";
			}
			break;
		case MainDataPickFragment.ADDTYPE_SUGAR:// 评价血糖 (float float1 , float
												// float2
			// 都有值)
			if (float1 <= 6.1 && float1 >= 3.9) {
				if (float2 < 3.9) {
					advise = "空腹血糖正常，餐后血糖偏低";
				} else if (float2 <= 9.4 && float2 >= 3.9) {
					advise = "您的血糖正常，请继续保持";
				} else {
					advise = "空腹血糖正常，餐后血糖偏高";
				}
			} else if (float1 < 3.9) {
				if (float2 < 3.9) {
					advise = "空腹血糖偏低，餐后血糖偏低";
				} else if (float2 <= 9.4 && float2 >= 3.9) {
					advise = "空腹血糖偏低，餐后血糖正常";
				} else {
					advise = "空腹血糖偏低，餐后血糖偏高";
				}
			} else {
				if (float2 < 3.9) {
					advise = "空腹血糖偏高，餐后血糖偏低";
				} else if (float2 <= 9.4 && float2 >= 3.9) {
					advise = "空腹血糖偏高，餐后血糖正常";
				} else {
					advise = "空腹血糖偏高，餐后血糖偏高";
				}
			}
			break;
		}
		return advise;
	}

	/**
	 * 判断一个指标是否是正常
	 * 
	 * @param addType
	 * @param value
	 * @return -1--偏低 0--正常 1---偏高
	 */
	public static int isNormal(int addType, float value) {
		int value_floor = Math.round(value);
		int isNoraml = 0;
		switch (addType) {
		case MainDataPickFragment.ADDTYPE_PLUS:// 评价 心率正常范围为60—100次/分。
			if (value_floor < 60)
				isNoraml = -1;
			if (value_floor > 100)
				isNoraml = 1;
			break;
		case MainDataPickFragment.ADDTYPE_PRESSURE_HIGH:// 高压90-140
			if (value_floor < 90)
				isNoraml = -1;
			if (value_floor > 140)
				isNoraml = 1;
			break;
		case MainDataPickFragment.ADDTYPE_PRESSURE_LOW:// 低压60--90
			if (value_floor < 60)
				isNoraml = -1;
			if (value_floor > 90)
				isNoraml = 1;
			break;
		case MainDataPickFragment.ADDTYPE_SUGAR_AFTERMEAL:// 评价餐后血糖
															// 餐后2小时血糖值：3.9-9.4毫摩/升。
			if (value < 3.9)
				isNoraml = -1;
			if (value - 9.4 > 0.05)
				// if(value>7.8)
				isNoraml = 1;
			break;
		case MainDataPickFragment.ADDTYPE_SUGAR_BEFOREMEAL:// 评价餐前血糖
															// 空腹血糖正常值：3.9-6.1毫摩尔/升。
			if (value < 3.9)
				isNoraml = -1;
			if (value > 6.1)
				isNoraml = 1;
			break;
		}
		return isNoraml;
	}

	/**
	 * 判断字符串是否是数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		for (int i = str.length(); --i >= 0;) {
			char c = str.charAt(i);
			if ('.' == c)
				continue;
			if (!Character.isDigit(c)) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 得到与指定日期相关的年、月，第一天与最后一天
	 * 
	 * @param date
	 *            某一天日期
	 * @return string[]格式 [0]当前月的第一天，[1]当前月的第二天
	 */
	public static String[] getYearMonth(Date date) {
		int year;
		int month;
		String firstDateString;
		String lastDateString;
		String firstday = "01", lastDay;
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		year = calendar.get(Calendar.YEAR);
		month = calendar.get(Calendar.MONTH) + 1;
		switch (month) {
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			lastDay = "31";
			break;
		case 2:
			lastDay = "28";
			break;
		default:
			lastDay = "30";
			break;
		}
		firstDateString = year + "-" + (month < 10 ? "0" + month : month) + "-"
				+ firstday;
		lastDateString = year + "-" + (month < 10 ? "0" + month : month) + "-"
				+ lastDay;
		return new String[] { firstDateString, lastDateString };
	}

	/**
	 * 计算并返回数组中的最大值
	 * 
	 * @param ds
	 */
	public static double getMaxValue(double[] ds) {
		double temp = 0;
		for (double d : ds) {
			if (d > temp)
				temp = d;
		}
		return temp;
	}

	/**
	 * 计算并返回数据中的最小值
	 * 
	 * @param ds
	 */
	public static double getMinValue(double[] ds) {
		double temp = 9999999d;
		for (double d : ds) {
			if (d < temp)
				temp = d;
		}
		return temp;
	}

	public static boolean compareTime(String str1, String str2) {

		int result = str1.compareTo(str2);
		if (result > 0)
			return true;
		else if (result == 0)
			return true;
		else
			return false;
	}

	/**
	 * 格式化日期
	 * 
	 * @param format
	 *            日期格式
	 * @param date
	 *            时间
	 * @return
	 */
	public static String getFormatDate(String format, Date date) {

		return new SimpleDateFormat(format).format(date);
	}

	/**
	 * 隐藏输入框
	 * 
	 * @param ctx
	 */
	public static void hiddenInput(Activity ctx) {
		InputMethodManager imm = (InputMethodManager) ctx
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		boolean isOpen = imm.isActive();// isOpen若返回true，则表示输入法打开
		if (isOpen) {
			((InputMethodManager) ctx
					.getSystemService(Context.INPUT_METHOD_SERVICE))
					.hideSoftInputFromWindow(ctx.getCurrentFocus()
							.getWindowToken(),
							InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

	/**
	 * 空list
	 */
	public static List<Object> nulllist = new ArrayList<Object>();
	static {
		nulllist.add(null);
	}

	/**
	 * 移除List空的item
	 */
	public static boolean listRemoveNull(Collection<?> list) {
		if (list != null) {
			return list.removeAll(nulllist);
		}
		return false;
	}

	/**
	 * 查询value在数组arr中的位置
	 * 
	 * @param arr
	 * @param value
	 * @return
	 */
	public static int getIdByArr(String[] arr, String value) {
		for (int i = 0; i < arr.length; i++) {
			if (arr[i].equals(value)) {
				return i;
			}
		}
		return 0;
	}

	private static SimpleDateFormat dateFormat = new SimpleDateFormat(
			"yyyy-MM-dd");

	// 获得当前月--开始日期
	public static String getMinMonthDate(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.DAY_OF_MONTH,
				calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
		return dateFormat.format(calendar.getTime());

	}

	// 获得当前月--结束日期(下个月+1)
	public static String getMaxMonthDate(Date date) {
		Calendar calendar = Calendar.getInstance();

		calendar.setTime(date);
		calendar.set(Calendar.DAY_OF_MONTH,
				calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
		return dateFormat.format(calendar.getTime());

	}

	// long时间转date格式化Str
	public static String long2DateStr(Long timeLong) {
		return dateFormat.format(new Date(timeLong));
	}

	/**
	 * 根据生日获得岁数
	 * 
	 * @param dateOfBirth
	 * @return
	 */
	public static int getAge(Date dateOfBirth) {
		int age = 0;
		Calendar born = Calendar.getInstance();
		Calendar now = Calendar.getInstance();
		if (dateOfBirth != null) {
			now.setTime(new Date());
			born.setTime(dateOfBirth);
			if (born.after(now)) {
				throw new IllegalArgumentException(
						"Can't be born in the future");
			}
			age = now.get(Calendar.YEAR) - born.get(Calendar.YEAR);
			if (now.get(Calendar.DAY_OF_YEAR) < born.get(Calendar.DAY_OF_YEAR)) {
				age -= 1;
			}
		}
		return age;

	}

	/**
	 * 获取时间差单位毫秒
	 * 
	 * @param date
	 * @return
	 */
	public static Long getTimeDifference(Date date) {

		Date nowDate = new Date();
		Long difference = nowDate.getTime() - date.getTime();
		return difference;
	}

	public static AlertDialog alertDialog;

	// 判断网络状态并弹出提示框
	public static boolean isNetConnectedDialog() {
		if (!CommonUtil.isNetConnected(MyConst.activity)) {
			alertDialog = DialogUtil.showNetConnectionDialog(MyConst.activity,
					new OnCallBackListener() {
						@Override
						public void clickLeftButton() {
							alertDialog.dismiss();
						}

						@Override
						public void clickRightButton() {
							alertDialog.dismiss();
						}
					});
			return false;
		}
		return true;
	}

	/**
	 * 替换List<Map<String,String>>中的null值
	 * 
	 * @param list
	 * @param str
	 */
	public static void null2Str(List<Map<String, String>> list, String str) {
		for (int i = 0; i < list.size(); i++) {
			for (String key : list.get(i).keySet()) {
				if (list.get(i).get(key) == null) {
					list.get(i).put(key, str);
				}
			}

		}
	}

	/**
	 * 返回昵称或真实姓名或id
	 * 
	 * @param nickName
	 * @param realName
	 * @param account
	 * @return
	 */
	public static String getName(String nickName, String realName,
			String account) {
		if (!TextUtils.isEmpty(nickName) && !nickName.equals("null")) {
			return nickName;
		}
		if (!TextUtils.isEmpty(realName) && !realName.equals("null")) {
			return realName;
		}
		return account;
	}

	/**
	 * 得到当前运行的Activity的名称
	 * 
	 * @return
	 */
	public static String getActivityName() {
		ActivityManager am = (ActivityManager) HealthApplication.getInstance()
				.getSystemService(Context.ACTIVITY_SERVICE);
		ComponentName cn = am.getRunningTasks(2).get(0).topActivity;
		String className = cn.getClassName();
		String rclassName = className.substring(className.lastIndexOf(".") + 1);
		return rclassName;
	}

	/**
	 * 得到Activity的名称
	 * 
	 * @return
	 */
	public static String getActivityNameByContext(Context context) {
		String activityName = context.toString();
		String rName = activityName.substring(
				activityName.lastIndexOf(".") + 1, activityName.indexOf("@"));
		return rName;
	}

	/**
	 * 得到Fragmen的名称
	 * 
	 * @return
	 */
	public static String getFragmentName(BaseFragment fragment) {
		String fragmentName = fragment.getClass().getName();

		String rName = fragmentName
				.substring(fragmentName.lastIndexOf(".") + 1);
		return rName;
	}
}
